<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Monitoring Parafrase (Mandiri)</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .modal, .toast { transition: opacity 0.3s ease, visibility 0.3s ease, transform 0.3s ease; }
        .modal.hidden, .toast.hidden { opacity: 0; visibility: hidden; transform: translateY(20px); }
        .status-belum-dikerjakan { background-color: #f3f4f6; color: #374151; }
        .status-dikerjakan { background-color: #fef9c3; color: #854d0e; }
        .status-revisi { background-color: #FF0000; color: #FFFFFF; } /* Diubah ke merah terang */
        .status-selesai { background-color: #dcfce7; color: #166534; }
        .status-menunggu-pembayaran { background-color: #e0e7ff; color: #3730a3; }
        .status-lunas { background-color: #cffafe; color: #0e7490; }

        /* Gaya untuk Indikator Deadline */
        .deadline-urgent { background-color: #FF0000; color: #FFFFFF; /* Diubah ke merah terang */ }
        .deadline-soon { background-color: #fef08a; /* yellow-200 */ }
        .deadline-passed { color: #9ca3af; text-decoration: line-through; }
    </style>
</head>
<body class="bg-gray-100 text-gray-800">

    <div id="app-container">
        <!-- App content will be rendered here by script after successful initialization -->
    </div>
    
    <!-- App Template. The entire UI is stored here and only loaded if Firebase connects. -->
    <template id="app-template">
         <div class="container mx-auto p-4 md:p-8">
            <header class="mb-6 flex flex-col md:flex-row justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">Dashboard Monitoring Proyek</h1>
                    <p class="text-gray-600 mt-1">Lacak semua progres parafrase di satu tempat.</p>
                    <p class="text-xs text-gray-500 mt-2">ID Sesi Anda: <span id="userIdDisplay" class="font-mono bg-gray-200 px-1 rounded">Memuat...</span></p>
                </div>
                <button id="addProjectBtn" class="mt-4 md:mt-0 w-full md:w-auto bg-indigo-600 text-white font-semibold py-2 px-4 rounded-lg shadow-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-75 flex items-center justify-center">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                    Tambah Proyek
                </button>
            </header>

            <!-- Filter Controls -->
            <div class="mb-4 p-4 bg-white rounded-lg shadow-sm">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 items-center">
                    <h3 class="font-semibold text-gray-700 lg:col-span-1">Filter:</h3>
                    <div class="w-full">
                        <label for="statusFilter" class="sr-only">Filter by Status</label>
                        <select id="statusFilter" class="w-full bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block p-2.5">
                            <option value="">Semua Status</option>
                            <option value="Belum Dikerjakan">Belum Dikerjakan</option>
                            <option value="Dikerjakan">Dikerjakan</option>
                            <option value="Revisi">Revisi</option>
                            <option value="Selesai">Selesai</option>
                        </select>
                    </div>
                    <div class="w-full">
                        <label for="adminFilter" class="sr-only">Filter by Admin</label>
                        <select id="adminFilter" class="w-full bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block p-2.5">
                            <option value="">Semua Admin</option>
                            <option value="BORNEOPCOM">BORNEOPCOM</option>
                            <option value="QUOTA PHRASE">QUOTA PHRASE</option>
                            <option value="SOBAT SKRIPSI">SOBAT SKRIPSI</option>
                        </select>
                    </div>
                    <div class="w-full">
                        <label for="teamFilter" class="sr-only">Filter by Team Member</label>
                        <select id="teamFilter" class="w-full bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block p-2.5">
                            <option value="">Semua Anggota Tim</option>
                        </select>
                    </div>
                    <div class="w-full">
                        <label for="dateFilter" class="sr-only">Filter Tanggal</label>
                        <input type="date" id="dateFilter" class="w-full bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block p-2.5">
                    </div>
                    <button id="resetFilters" class="w-full lg:col-start-5 bg-gray-200 text-gray-700 font-semibold py-2 px-4 rounded-lg hover:bg-gray-300">Reset Filter</button>
                </div>
                 <!-- Deadline Legend -->
                <div class="flex items-center flex-wrap gap-x-4 gap-y-2 text-xs text-gray-600 mt-4 pt-2 border-t">
                    <span class="font-semibold">Keterangan Deadline:</span>
                    <div class="flex items-center"><span class="w-3 h-3 rounded-full bg-red-500 mr-1.5"></span>Mendesak (&lt; 24 jam)</div>
                    <div class="flex items-center"><span class="w-3 h-3 rounded-full bg-yellow-200 mr-1.5"></span>Segera (&lt; 3 hari)</div>
                    <div class="flex items-center"><span class="w-3 h-3 rounded-full border bg-white mr-1.5"></span>Aman</div>
                    <div class="flex items-center"><span class="font-mono text-gray-400 mr-1.5"><s>T</s></span>Lewat</div>
                </div>
            </div>

            <!-- Projects Table -->
            <div class="bg-white rounded-lg shadow-lg overflow-x-auto">
                <table class="w-full text-sm text-left text-gray-600">
                    <thead class="text-xs text-gray-700 uppercase bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3">No.</th>
                            <th scope="col" class="px-6 py-3">No Pesanan Marketplace</th>
                            <th scope="col" class="px-6 py-3">File / Judul</th>
                            <th scope="col" class="px-6 py-3">File Asli</th>
                            <th scope="col" class="px-6 py-3">Admin</th>
                            <th scope="col" class="px-6 py-3">Anggota Tim</th>
                            <th scope="col" class="px-6 py-3">Deadline</th>
                            <th scope="col" class="px-6 py-3">Status</th>
                            <th scope="col" class="px-6 py-3">Hasil Kerja</th>
                            <th scope="col" class="px-6 py-3 text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="projectsTableBody">
                        <tr><td colspan="10" class="text-center p-8 text-gray-500">Memuat data proyek...</td></tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Add/Edit Project Modal -->
        <div id="projectModal" class="modal hidden fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center p-4">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-lg p-6" onclick="event.stopPropagation()">
                <h2 id="modalTitle" class="text-2xl font-bold mb-4">Tambah Proyek Baru</h2>
                <form id="projectForm">
                    <input type="hidden" id="projectId">
                    <div class="mt-4">
                        <label for="orderNumber" class="block mb-2 text-sm font-medium text-gray-900">No. Pesanan</label>
                        <input type="text" id="orderNumber" placeholder="Contoh: 001, A01" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5" required>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
                        <div>
                            <label for="shopeeOrderNumber" class="block mb-2 text-sm font-medium text-gray-900">No Pesanan Marketplace</label>
                            <input type="text" id="shopeeOrderNumber" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5" required>
                        </div>
                         <div>
                            <label for="adminName" class="block mb-2 text-sm font-medium text-gray-900">Nama Admin</label>
                            <select id="adminName" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5" required>
                                <option value="">Pilih Admin</option>
                                <option value="BORNEOPCOM">BORNEOPCOM</option>
                                <option value="QUOTA PHRASE">QUOTA PHRASE</option>
                                <option value="SOBAT SKRIPSI">SOBAT SKRIPSI</option>
                            </select>
                        </div>
                    </div>
                     <div class="mt-4">
                        <label for="teamMember" class="block mb-2 text-sm font-medium text-gray-900">Anggota Tim</label>
                        <input type="text" id="teamMember" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5" required>
                    </div>
                    <div class="mt-4">
                        <label for="fileName" class="block mb-2 text-sm font-medium text-gray-900">Nama File / Judul Skripsi</label>
                        <input type="text" id="fileName" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5" required>
                    </div>
                    <div class="mt-4">
                        <label for="originalFileLink" class="block mb-2 text-sm font-medium text-gray-900">Link File Asli (Google Drive, dll)</label>
                        <input type="url" id="originalFileLink" placeholder="https://..." class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5">
                    </div>
                    <div class="mt-4">
                        <label for="deadline" class="block mb-2 text-sm font-medium text-gray-900">Deadline (Tanggal & Jam)</label>
                        <input type="datetime-local" id="deadline" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5" required>
                    </div>
                    <div class="mt-4">
                        <label for="notes" class="block mb-2 text-sm font-medium text-gray-900">Catatan (opsional)</label>
                        <textarea id="notes" rows="3" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-full p-2.5"></textarea>
                    </div>
                    <div class="flex justify-end gap-4 mt-6">
                        <button type="button" id="cancelBtn" class="py-2 px-4 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">Batal</button>
                        <button type="submit" class="py-2 px-4 bg-indigo-600 text-white font-semibold rounded-lg hover:bg-indigo-700">Simpan</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Custom Confirm Modal -->
        <div id="confirmModal" class="modal hidden fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center p-4">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-sm p-6 text-center">
                <h3 class="text-lg font-semibold mb-2">Konfirmasi Penghapusan</h3>
                <p class="text-gray-600 mb-6">Apakah Anda yakin ingin menghapus proyek ini?</p>
                <div class="flex justify-center gap-4">
                    <button id="confirmCancelBtn" class="py-2 px-6 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">Batal</button>
                    <button id="confirmDeleteBtn" class="py-2 px-6 bg-red-600 text-white rounded-lg hover:bg-red-700">Ya, Hapus</button>
                </div>
            </div>
        </div>

        <!-- Toast Notification -->
        <div id="toast" class="toast hidden fixed bottom-5 right-5 flex items-center w-full max-w-xs p-4 space-x-4 text-gray-500 bg-white divide-x divide-gray-200 rounded-lg shadow" role="alert">
            <div id="toast-message" class="text-sm font-normal">Message</div>
        </div>
    </template>
    
    <script type="module">
        // --- Firebase Module Imports ---
        import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";
        import { getFirestore, collection, doc, addDoc, onSnapshot, updateDoc, deleteDoc, serverTimestamp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";
        import { getAuth, signInAnonymously, onAuthStateChanged, signInWithCustomToken } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";
        
        // --- Global State ---
        let projects = [];
        let currentUserId = null;
        let currentFilters = { status: '', teamMember: '', date: '', adminName: '' };
        let projectsCollectionRef;
        let toastTimeout;
        let db, auth;

        // --- DOM Elements ---
        let addProjectBtn, projectModal, modalTitle, projectForm, cancelBtn, tableBody, 
            statusFilter, teamFilter, adminFilter, dateFilter, resetFiltersBtn, userIdDisplay, 
            confirmModal, confirmCancelBtn, confirmDeleteBtn, toast, toastMessage;

        // --- UI Functions ---
        function showToast(message, type = 'error') {
            if (!toast || !toastMessage) return;
            clearTimeout(toastTimeout);
            toastMessage.textContent = message;
            toast.className = 'toast fixed bottom-5 right-5 flex items-center w-full max-w-xs p-4 space-x-4 rounded-lg shadow';
            if (type === 'success') {
                toast.classList.add('bg-green-100', 'text-green-800');
            } else {
                toast.classList.add('bg-red-100', 'text-red-800');
            }
            toast.classList.remove('hidden');
            toastTimeout = setTimeout(() => {
                toast.classList.add('hidden');
            }, 4000);
        }

        function renderErrorState(title, message, details = '') {
            const appContainer = document.getElementById('app-container');
            appContainer.innerHTML = `<div class="p-4 text-center text-red-700 bg-red-100 h-screen flex flex-col justify-center items-center">
                <h1 class="text-xl font-bold">${title}</h1>
                <p class="mt-2">${message}</p>
                <p class="mt-1 text-sm text-gray-600">${details}</p>
            </div>`;
        }
        
        // --- Main Application Logic ---
        function initializeAppUI() {
            const template = document.getElementById('app-template');
            const appContainer = document.getElementById('app-container');
            appContainer.innerHTML = template.innerHTML;

            // Assign DOM elements now that they exist in the DOM
            addProjectBtn = document.getElementById('addProjectBtn');
            projectModal = document.getElementById('projectModal');
            modalTitle = document.getElementById('modalTitle');
            projectForm = document.getElementById('projectForm');
            cancelBtn = document.getElementById('cancelBtn');
            tableBody = document.getElementById('projectsTableBody');
            statusFilter = document.getElementById('statusFilter');
            teamFilter = document.getElementById('teamFilter');
            adminFilter = document.getElementById('adminFilter');
            dateFilter = document.getElementById('dateFilter');
            resetFiltersBtn = document.getElementById('resetFilters');
            userIdDisplay = document.getElementById('userIdDisplay');
            confirmModal = document.getElementById('confirmModal');
            confirmCancelBtn = document.getElementById('confirmCancelBtn');
            confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
            toast = document.getElementById('toast');
            toastMessage = document.getElementById('toast-message');

            // Attach Event Listeners
            addProjectBtn.addEventListener('click', () => openModal());
            cancelBtn.addEventListener('click', closeModal);
            projectModal.addEventListener('click', (e) => { if (e.target === projectModal) closeModal(); });
            projectForm.addEventListener('submit', handleFormSubmit);
            confirmCancelBtn.addEventListener('click', () => confirmModal.classList.add('hidden'));
            statusFilter.addEventListener('change', applyFilters);
            teamFilter.addEventListener('change', applyFilters);
            adminFilter.addEventListener('change', applyFilters);
            dateFilter.addEventListener('change', applyFilters);
            resetFiltersBtn.addEventListener('click', () => {
                statusFilter.value = "";
                teamFilter.value = "";
                adminFilter.value = "";
                dateFilter.value = "";
                applyFilters();
            });

            // Start authentication and data loading
            initializeAuthAndData();
        }

        async function initializeAuthAndData() {
            onAuthStateChanged(auth, user => {
                if (user) {
                    currentUserId = user.uid;
                    if(userIdDisplay) userIdDisplay.textContent = currentUserId;
                    // Use a static App ID to ensure both dashboards are in sync
                    const appId = 'standalone-parafrase-app';
                    projectsCollectionRef = collection(db, `artifacts/${appId}/public/data/projects`);
                    listenForProjects();
                } else {
                    currentUserId = null;
                    if(userIdDisplay) userIdDisplay.textContent = "Sesi tidak valid";
                }
            });
            
            // Robust Authentication with Fallback
            try {
                if (typeof __initial_auth_token !== 'undefined' && __initial_auth_token) {
                    await signInWithCustomToken(auth, __initial_auth_token);
                } else {
                    await signInAnonymously(auth);
                }
            } catch (error) {
                console.warn("Gagal masuk dengan token, mencoba masuk secara anonim.", error);
                try {
                    await signInAnonymously(auth);
                } catch (anonError) {
                    console.error("KRITIS: Gagal masuk secara anonim juga.", anonError);
                     renderErrorState(
                        "Gagal Memulai Sesi",
                        "Tidak dapat membuat sesi pengguna. Aplikasi tidak dapat berjalan.",
                        anonError.message
                    );
                }
            }
        }
        
        function openModal(project = null) {
            projectForm.reset();
            document.getElementById('projectId').value = project ? project.id : '';
            modalTitle.textContent = project ? 'Edit Proyek' : 'Tambah Proyek Baru';
            if (project) {
                document.getElementById('orderNumber').value = project.orderNumber || '';
                document.getElementById('shopeeOrderNumber').value = project.shopeeOrderNumber || '';
                document.getElementById('adminName').value = project.adminName || '';
                document.getElementById('fileName').value = project.fileName || '';
                document.getElementById('originalFileLink').value = project.originalFileLink || '';
                document.getElementById('teamMember').value = project.teamMember || '';
                document.getElementById('deadline').value = project.deadline || '';
                document.getElementById('notes').value = project.notes || '';
            }
            projectModal.classList.remove('hidden');
        }

        function closeModal() {
            projectModal.classList.add('hidden');
        }

        async function handleFormSubmit(e) {
            e.preventDefault();
            if(!currentUserId) {
                showToast("Gagal menyimpan: Sesi Anda tidak valid. Silakan muat ulang halaman.", "error");
                return;
            }
            const id = document.getElementById('projectId').value;
            const projectData = {
                orderNumber: document.getElementById('orderNumber').value,
                shopeeOrderNumber: document.getElementById('shopeeOrderNumber').value,
                adminName: document.getElementById('adminName').value,
                fileName: document.getElementById('fileName').value,
                originalFileLink: document.getElementById('originalFileLink').value,
                teamMember: document.getElementById('teamMember').value,
                deadline: document.getElementById('deadline').value,
                notes: document.getElementById('notes').value,
                updatedAt: serverTimestamp()
            };

            try {
                if (id) {
                    const projectRef = doc(projectsCollectionRef, id);
                    await updateDoc(projectRef, projectData);
                    showToast('Proyek berhasil diperbarui!', 'success');
                } else {
                    projectData.status = 'Belum Dikerjakan';
                    projectData.createdAt = serverTimestamp();
                    await addDoc(projectsCollectionRef, projectData);
                    showToast('Proyek baru berhasil ditambahkan!', 'success');
                }
                closeModal();
            } catch (error) {
                console.error("Gagal menyimpan proyek: ", error);
                showToast(`Gagal menyimpan proyek: ${error.message}`, 'error');
            }
        }
        
        async function updateProjectStatus(id, newStatus) {
            try {
                 const projectRef = doc(projectsCollectionRef, id);
                 await updateDoc(projectRef, { status: newStatus, updatedAt: serverTimestamp() });
                 showToast('Status berhasil diperbarui!', 'success');
            } catch(error) {
                console.error("Gagal memperbarui status: ", error);
                showToast('Gagal memperbarui status.', 'error');
            }
        }

        function promptDelete(id) {
            confirmModal.classList.remove('hidden');
            const newConfirmBtn = confirmDeleteBtn.cloneNode(true);
            confirmDeleteBtn.replaceWith(newConfirmBtn);
            
            newConfirmBtn.addEventListener('click', async () => {
                try {
                    await deleteDoc(doc(projectsCollectionRef, id));
                    showToast('Proyek berhasil dihapus.', 'success');
                } catch(error) {
                    console.error("Gagal menghapus proyek: ", error);
                    showToast('Gagal menghapus proyek.', 'error');
                } finally {
                    confirmModal.classList.add('hidden');
                }
            });
        }
        
        function listenForProjects() {
             if(!projectsCollectionRef) return;
             onSnapshot(projectsCollectionRef, (snapshot) => {
                projects = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
                projects.sort((a, b) => (b.createdAt?.toMillis() || 0) - (a.createdAt?.toMillis() || 0));
                updateFilterOptions();
                renderTable();
            }, (error) => {
                console.error("Error mendengarkan perubahan proyek:", error);
                showToast("Gagal memuat data proyek.", "error");
            });
        }
        
        function getStatusClass(status) {
            const statusMap = {
                'Belum Dikerjakan': 'status-belum-dikerjakan', 'Dikerjakan': 'status-dikerjakan',
                'Revisi': 'status-revisi', 'Selesai': 'status-selesai',
            };
            return statusMap[status] || 'status-belum-dikerjakan';
        }

        function renderTable() {
            if (!tableBody) return;
            tableBody.innerHTML = '';
            const filteredProjects = projects.filter(p => {
                const statusMatch = !currentFilters.status || p.status === currentFilters.status;
                const teamMatch = !currentFilters.teamMember || p.teamMember === currentFilters.teamMember;
                const adminMatch = !currentFilters.adminName || p.adminName === currentFilters.adminName;
                const dateMatch = !currentFilters.date || (p.deadline && p.deadline.startsWith(currentFilters.date));
                return statusMatch && teamMatch && adminMatch && dateMatch;
            });

            if (filteredProjects.length === 0) {
                tableBody.innerHTML = `<tr><td colspan="10" class="text-center p-8 text-gray-500">${projects.length > 0 ? 'Tidak ada proyek yang cocok dengan filter.' : 'Belum ada proyek. Klik "Tambah Proyek" untuk memulai.'}</td></tr>`;
                return;
            }

            filteredProjects.forEach(project => {
                const tr = document.createElement('tr');
                tr.className = "bg-white border-b hover:bg-gray-50";
                
                const deadlineDate = project.deadline ? new Date(project.deadline).toLocaleString('id-ID', { 
                    weekday: 'long',
                    year: 'numeric', month: 'long', day: 'numeric',
                    hour: '2-digit', minute: '2-digit', hour12: false
                }).replace(/\./g, ':').replace(' pukul ', ', ') : 'N/A';

                const originalFileLinkHTML = project.originalFileLink
                    ? `<a href="${project.originalFileLink}" target="_blank" class="text-indigo-600 hover:text-indigo-800 hover:underline">Buka File</a>`
                    : `<span class="text-gray-400">-</span>`;

                const fileLinkHTML = project.fileHasilKerja 
                    ? `<a href="${project.fileHasilKerja}" target="_blank" class="text-indigo-600 hover:text-indigo-800 hover:underline">Lihat File</a>`
                    : `<span class="text-gray-400">-</span>`;
                
                tr.innerHTML = `
                    <td class="px-6 py-4 font-bold">${project.orderNumber || ''}</td>
                    <td class="px-6 py-4 font-medium text-gray-900">${project.shopeeOrderNumber || ''}</td>
                    <td class="px-6 py-4">${project.fileName || ''}</td>
                    <td class="px-6 py-4">${originalFileLinkHTML}</td>
                    <td class="px-6 py-4">${project.adminName || ''}</td>
                    <td class="px-6 py-4">${project.teamMember || ''}</td>
                    <td class="px-6 py-4 deadline-cell">${deadlineDate}</td>
                    <td class="px-6 py-4">
                         <select class="status-select border-0 rounded-lg text-sm p-1 cursor-pointer" data-id="${project.id}">
                            <option value="Belum Dikerjakan" ${project.status === 'Belum Dikerjakan' ? 'selected' : ''}>Belum Dikerjakan</option>
                            <option value="Dikerjakan" ${project.status === 'Dikerjakan' ? 'selected' : ''}>Dikerjakan</option>
                            <option value="Revisi" ${project.status === 'Revisi' ? 'selected' : ''}>Revisi</option>
                            <option value="Selesai" ${project.status === 'Selesai' ? 'selected' : ''}>Selesai</option>
                        </select>
                    </td>
                    <td class="px-6 py-4">${fileLinkHTML}</td>
                    <td class="px-6 py-4 text-center">
                        <button class="edit-btn p-1 text-indigo-600 hover:text-indigo-900" title="Edit Proyek"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg></button>
                        <button class="delete-btn p-1 text-red-600 hover:text-red-900 ml-2" title="Hapus Proyek"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg></button>
                    </td>
                `;

                // Apply deadline styling
                const deadlineCell = tr.querySelector('.deadline-cell');
                const now = new Date();
                const deadline = project.deadline ? new Date(project.deadline) : null;
                const isCompleted = project.status === 'Selesai';

                if (deadline && !isCompleted) {
                    const diffHours = (deadline.getTime() - now.getTime()) / (1000 * 60 * 60);

                    if (diffHours < 0) {
                        deadlineCell.classList.add('deadline-passed');
                    } else if (diffHours <= 24) {
                        deadlineCell.classList.add('deadline-urgent');
                    } else if (diffHours <= 72) { // 3 days
                        deadlineCell.classList.add('deadline-soon');
                    }
                }

                const statusSelect = tr.querySelector('.status-select');
                statusSelect.className = 'status-select border-0 rounded-lg text-sm p-1 cursor-pointer ' + getStatusClass(project.status);
                statusSelect.addEventListener('change', (e) => updateProjectStatus(e.target.dataset.id, e.target.value));
                tr.querySelector('.edit-btn').addEventListener('click', () => openModal(project));
                tr.querySelector('.delete-btn').addEventListener('click', () => promptDelete(project.id));
                tableBody.appendChild(tr);
            });
        }

        function applyFilters() {
            currentFilters.status = statusFilter.value;
            currentFilters.teamMember = teamFilter.value;
            currentFilters.adminName = adminFilter.value;
            currentFilters.date = dateFilter.value;
            renderTable();
        }

        function updateFilterOptions() {
            if (!teamFilter || !adminFilter) return;
            const teamMembers = [...new Set(projects.map(p => p.teamMember).filter(Boolean))];
            
            const currentTeamSelection = teamFilter.value;
            teamFilter.innerHTML = '<option value="">Semua Anggota Tim</option>';
            teamMembers.sort().forEach(member => {
                const option = document.createElement('option');
                option.value = member;
                option.textContent = member;
                teamFilter.appendChild(option);
            });
            teamFilter.value = currentTeamSelection;

        }

        // --- Entry Point ---
        document.addEventListener('DOMContentLoaded', () => {
            try {
                let firebaseConfig;

                // Check if running inside the Gemini environment with provided config
                if (typeof __firebase_config !== 'undefined' && __firebase_config) {
                    firebaseConfig = JSON.parse(__firebase_config);
                } else {
                    // Fallback to standalone configuration
                    const standaloneConfig = {
                        apiKey: "AIzaSyYOUR_API_KEY_HERE",
                        authDomain: "your-project-id.firebaseapp.com",
                        projectId: "your-project-id",
                        storageBucket: "your-project-id.appspot.com",
                        messagingSenderId: "your-sender-id",
                        appId: "your-app-id"
                    };

                    // Check if the user has replaced the placeholder values
                    if (standaloneConfig.apiKey === "AIzaSyYOUR_API_KEY_HERE") {
                        renderErrorState(
                            "Konfigurasi Belum Diatur",
                            "Untuk menjalankan aplikasi ini secara mandiri (di luar platform ini), Anda perlu mengganti placeholder konfigurasi Firebase di dalam file HTML.",
                            "Silakan buat proyek Firebase Anda sendiri dan salin-tempel konfigurasinya ke dalam variabel 'standaloneConfig'."
                        );
                        return; // Stop execution
                    }
                    firebaseConfig = standaloneConfig;
                }

                const app = initializeApp(firebaseConfig);
                db = getFirestore(app);
                auth = getAuth(app);

                initializeAppUI();

            } catch (error) {
                console.error("CRITICAL ERROR on startup:", error);
                renderErrorState(
                    "Gagal Memuat Aplikasi", 
                    "Tidak dapat terhubung ke database. Ini bisa terjadi karena konfigurasi yang salah atau masalah jaringan.",
                    error.message
                );
            }
        });

    </script>
</body>
</html>
